package com.test.deencredit.view_deencredit.process_widget_deencredit;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;

import com.test.deencredit.R;
import com.test.deencredit.base_deencredit.BaseApplication_deencredit;
import com.test.deencredit.base_deencredit.BaseProcessWidgetManager_deencredit;
import com.test.deencredit.bean_deencredit.process_deencredit.ProcessInfo_Data_deencredit;
import com.test.deencredit.bean_deencredit.userinfo_deencredit.OthersInfo_deencredit;
import com.test.deencredit.config_deencredit.Constant_deencredit;
import com.test.deencredit.config_deencredit.PermissionConfig_deencredit;
import com.test.deencredit.dialog_deencredit.PhotoSelectorDialog_deencredit;
import com.test.deencredit.util_deencredit.http_deencredit.HttpUtil_deencredit;
import com.test.deencredit.util_deencredit.image_deencredit.ImageConvert_deencredit;

import java.io.File;
import java.util.TreeMap;

import pub.devrel.easypermissions.EasyPermissions;

public class OcrViewManager_deencredit extends BaseProcessWidgetManager_deencredit {

    private FragmentActivity activity_deencredit;

    private View idcardView_deencredit, passportView_deencredit, drvinglicenseView_deencredit;
    private ImageView idcardIv_deencredit, passportIv_deencredit, drvinglicenseIv_deencredit;
    private TextView imgTypeTitleTv_deencredit;
    private ImageButton img1Ib_deencredit, img2Ib_deencredit;
    private TextView img1Tv_deencredit, img2Tv_deencredit;
    private View img2View_deencredit;

    private String image1Url_deencredit, image2Url_deencredit;
    private Bitmap image1Bitmap_deencredit, image2Bitmap_deencredit;

    private boolean isImageReverse_deencredit = false;

    private static final String CT_IdCard_deencredit ="National ID card", CT_Passport_deencredit ="Passport", CT_DrvingLicense_deencredit ="Drving license";
    private static final String WD_IdCard_deencredit ="IDCARD", WD_Passport_deencredit ="PASSPORT", WD_DrvingLicense_deencredit ="DRIVING";

    private String selectType_deencredit = CT_IdCard_deencredit;

    private Runnable startCameraRunnable_deencredit;

    public String imgPath_deencredit = "";
    public Uri photoUri_deencredit;

    public static final int Flag_StartCamera_deencredit = 77;

    private ActivityResultLauncher<PickVisualMediaRequest> pickMedia_deencredit;

    private final Runnable processRespRunnable_deencredit, imgUploadRespRunnable_deencredit;

    public OcrViewManager_deencredit(View view, ProcessInfo_Data_deencredit data, String page, Runnable processRespRunnable, Runnable imgUploadRespRunnable){
        super(view,data,page);
        activity_deencredit = (FragmentActivity) mView_deencredit.getContext();

        this.processRespRunnable_deencredit = processRespRunnable;
        this.imgUploadRespRunnable_deencredit = imgUploadRespRunnable;
    }

    @Override
    protected void init_deencredit(){

        idcardView_deencredit = mView_deencredit.findViewById(R.id.vpo_view_idcard);
        passportView_deencredit = mView_deencredit.findViewById(R.id.vpo_view_passport);
        drvinglicenseView_deencredit = mView_deencredit.findViewById(R.id.vpo_view_drvinglicense);
        idcardIv_deencredit = mView_deencredit.findViewById(R.id.vpo_iv_idcard);
        passportIv_deencredit = mView_deencredit.findViewById(R.id.vpo_iv_passport);
        drvinglicenseIv_deencredit = mView_deencredit.findViewById(R.id.vpo_iv_drvinglicense);
        imgTypeTitleTv_deencredit = mView_deencredit.findViewById(R.id.vpo_tv_img_type_title);
        img1Ib_deencredit = mView_deencredit.findViewById(R.id.vpo_ib_img1);
        img2Ib_deencredit = mView_deencredit.findViewById(R.id.vpo_ib_img2);
        img1Tv_deencredit = mView_deencredit.findViewById(R.id.vpo_tv_img1);
        img2Tv_deencredit = mView_deencredit.findViewById(R.id.vpo_tv_img2);
        img2View_deencredit = mView_deencredit.findViewById(R.id.vpo_view_img2);
        
        img1Ib_deencredit.setOnClickListener(v -> {

            HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"IMAGE_1_CLICK","");

            new PhotoSelectorDialog_deencredit(
                    mView_deencredit.getContext(),
                    () -> {//打开相机
                        isImageReverse_deencredit = false;
                        startCamera();
                    },
                    () -> {//相册选择
                        isImageReverse_deencredit = false;
                        openAlbum();
                    }
            ).show();

        });

        img2Ib_deencredit.setOnClickListener(v -> {
            HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"IMAGE_2_CLICK","");

            new PhotoSelectorDialog_deencredit(
                    mView_deencredit.getContext(),
                    () -> {//打开相机
                        isImageReverse_deencredit = true;
                        startCamera();
                    },
                    () -> {//相册选择
                        isImageReverse_deencredit = true;
                        openAlbum();
                    }
            ).show();

        });

        idcardView_deencredit.setOnClickListener(v -> initTypeIdCard_deencredit());
        passportView_deencredit.setOnClickListener(v -> initTypePassport_deencredit());
        drvinglicenseView_deencredit.setOnClickListener(v -> initTypeDrvingLicense_deencredit());

        initTypeIdCard_deencredit();
        
    }

    public void nextClick_deencredit(String path){
        if (TextUtils.isEmpty(image1Url_deencredit)||(TextUtils.isEmpty(image2Url_deencredit)&&!selectType_deencredit.equalsIgnoreCase(CT_Passport_deencredit))){
            Toast.makeText(mView_deencredit.getContext(), mView_deencredit.getContext().getString(R.string.upload_ocr_tip_deencredit),Toast.LENGTH_SHORT).show();
            return;
        }

        HttpUtil_deencredit.getInstance_deencredit().submitProcessInfo_deencredit(
                activity_deencredit,
                path,
                new TreeMap<String,String>(){{
                    put("cardImgUrl", image1Url_deencredit);
                    put("cardBackImgUrl", selectType_deencredit.equalsIgnoreCase(CT_Passport_deencredit) ? "": image2Url_deencredit);
                    put("cardType", getTypeWd_deencredit());
                }},
                () -> HttpUtil_deencredit.getInstance_deencredit().userProcess_deencredit(activity_deencredit,() -> {if (processRespRunnable_deencredit !=null) processRespRunnable_deencredit.run();}
        ));
    }

    @Override
    public boolean checkInput_deencredit() {
        return false;
    }

    @Override
    public String getInput_deencredit() {
        return "";
    }


    private void startCamera(){

        HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"START_CAMERA_CLICK","");

        //拍照流程
        startCameraRunnable_deencredit = () -> {
            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

            String imageFilePath = this.getImageFilePath_deencredit();
            File imageFile = new File(imageFilePath);
            imgPath_deencredit = imageFilePath;
            String providerAuthority = BaseApplication_deencredit.getInstant().getPackageName() + ".file_provider";
            photoUri_deencredit = FileProvider.getUriForFile(BaseApplication_deencredit.getInstant(), providerAuthority, imageFile);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri_deencredit);
            if (activity_deencredit !=null) activity_deencredit.startActivityForResult(intent, Flag_StartCamera_deencredit);
        };
        //申请权限
        if (!PermissionConfig_deencredit.checkPermissions_deencredit(mView_deencredit.getContext(), Manifest.permission.CAMERA)) {
            if (activity_deencredit !=null)
                EasyPermissions.requestPermissions(activity_deencredit, "App requires camera permission.", PermissionConfig_deencredit.PermissionCode_Camera_deencredit, Manifest.permission.CAMERA);
        } else startCameraRunnable_deencredit.run();
    }

    private void openAlbum(){

        HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"OPEN_ALBUM_CLICK","");

        if (pickMedia_deencredit !=null)
            pickMedia_deencredit.launch(
                    new PickVisualMediaRequest.Builder()
                            .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                            .build()
            );
    }

    public void setPickMedia_deencredit(ActivityResultLauncher<PickVisualMediaRequest> pickMedia_deencredit) {
        this.pickMedia_deencredit = pickMedia_deencredit;
    }

    public void onPhotoGet_deencredit() {
        if (photoUri_deencredit == null) {
            if (isImageReverse_deencredit) image2Url_deencredit = null;
            else image1Url_deencredit = null;
            Toast.makeText(mView_deencredit.getContext(), mView_deencredit.getContext().getString(R.string.photo_upload_again_tip_deencredit),Toast.LENGTH_SHORT).show();
            return;
        }

        if (!TextUtils.isEmpty(imgPath_deencredit)) {
            ImageConvert_deencredit.startConvertImage_deencredit(
                    new File(imgPath_deencredit),
                    (localPath, thumpImg) -> {
                        if (isImageReverse_deencredit) image2Bitmap_deencredit = thumpImg;
                        else image1Bitmap_deencredit = thumpImg;
                        new Thread(() -> HttpUtil_deencredit.getInstance_deencredit().uploadImg_deencredit(activity_deencredit,localPath,() -> {
                            if (imgUploadRespRunnable_deencredit !=null) imgUploadRespRunnable_deencredit.run();
                        })).start();
                    }
            );
        } else {
            if (isImageReverse_deencredit) image2Url_deencredit = null;
            else image1Url_deencredit = null;
            Toast.makeText(mView_deencredit.getContext(), mView_deencredit.getContext().getString(R.string.photo_upload_again_tip_deencredit),Toast.LENGTH_SHORT).show();
        }
    }

    public void onPhotoUploadResponse_deencredit(){

        String imagePath = OthersInfo_deencredit.getInstance_deencredit().getImgPath_deencredit();

        if (TextUtils.isEmpty(imagePath)||(!isImageReverse_deencredit && image1Bitmap_deencredit ==null)||(isImageReverse_deencredit && image2Bitmap_deencredit ==null)){
            Toast.makeText(mView_deencredit.getContext(), mView_deencredit.getContext().getString(R.string.photo_upload_again_tip_deencredit),Toast.LENGTH_SHORT).show();
            return;
        }

        if (isImageReverse_deencredit){
            this.image2Url_deencredit = imagePath;
            img2Ib_deencredit.setImageBitmap(image2Bitmap_deencredit);
        }else {
            this.image1Url_deencredit = imagePath;
            img1Ib_deencredit.setImageBitmap(image1Bitmap_deencredit);
        }
    }

    @SuppressLint("SetTextI18n")
    private void initTypeIdCard_deencredit(){

        HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"TYPE_ID_CARD_CLICK","");

        idcardView_deencredit.setBackgroundResource(R.drawable.bg_purple_t_rc10dp_border_purple_1dp_deencredit);
        passportView_deencredit.setBackgroundResource(R.drawable.bg_gray_rc10dp_deencredit);
        drvinglicenseView_deencredit.setBackgroundResource(R.drawable.bg_gray_rc10dp_deencredit);
        idcardIv_deencredit.setBackgroundResource(R.drawable.icon_check_true_deencredit);
        passportIv_deencredit.setBackgroundResource(R.drawable.icon_check_false_deencredit);
        drvinglicenseIv_deencredit.setBackgroundResource(R.drawable.icon_check_false_deencredit);

        imgTypeTitleTv_deencredit.setText(mView_deencredit.getContext().getString(R.string.ocr_type_idcard_deencredit));

        clearImg_deencredit();

        selectType_deencredit = CT_IdCard_deencredit;
        img1Tv_deencredit.setText(mView_deencredit.getContext().getString(R.string.ocr_idcard_front_deencredit));
        img2Tv_deencredit.setText(mView_deencredit.getContext().getString(R.string.ocr_idcard_back_deencredit));
        img2View_deencredit.setVisibility(View.VISIBLE);
    }

    @SuppressLint("SetTextI18n")
    private void initTypePassport_deencredit(){

        HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"TYPE_PASSPORT_CLICK","");

        idcardView_deencredit.setBackgroundResource(R.drawable.bg_gray_rc10dp_deencredit);
        passportView_deencredit.setBackgroundResource(R.drawable.bg_purple_t_rc10dp_border_purple_1dp_deencredit);
        drvinglicenseView_deencredit.setBackgroundResource(R.drawable.bg_gray_rc10dp_deencredit);
        idcardIv_deencredit.setBackgroundResource(R.drawable.icon_check_false_deencredit);
        passportIv_deencredit.setBackgroundResource(R.drawable.icon_check_true_deencredit);
        drvinglicenseIv_deencredit.setBackgroundResource(R.drawable.icon_check_false_deencredit);

        imgTypeTitleTv_deencredit.setText(mView_deencredit.getContext().getString(R.string.ocr_type_passport_deencredit));

        clearImg_deencredit();

        selectType_deencredit = CT_Passport_deencredit;
        img1Tv_deencredit.setText(mView_deencredit.getContext().getString(R.string.ocr_passport_deencredit));
        img2View_deencredit.setVisibility(View.GONE);

    }

    @SuppressLint("SetTextI18n")
    private void initTypeDrvingLicense_deencredit(){

        HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"TYPE_DRIVING_LICENSE_CLICK","");

        idcardView_deencredit.setBackgroundResource(R.drawable.bg_gray_rc10dp_deencredit);
        passportView_deencredit.setBackgroundResource(R.drawable.bg_gray_rc10dp_deencredit);
        drvinglicenseView_deencredit.setBackgroundResource(R.drawable.bg_purple_t_rc10dp_border_purple_1dp_deencredit);
        idcardIv_deencredit.setBackgroundResource(R.drawable.icon_check_false_deencredit);
        passportIv_deencredit.setBackgroundResource(R.drawable.icon_check_false_deencredit);
        drvinglicenseIv_deencredit.setBackgroundResource(R.drawable.icon_check_true_deencredit);

        imgTypeTitleTv_deencredit.setText(mView_deencredit.getContext().getString(R.string.ocr_type_drvinglicense_deencredit));

        clearImg_deencredit();

        selectType_deencredit = CT_DrvingLicense_deencredit;
        img1Tv_deencredit.setText(mView_deencredit.getContext().getString(R.string.ocr_drvinglicense_front_deencredit));
        img2Tv_deencredit.setText(mView_deencredit.getContext().getString(R.string.ocr_drvinglicense_back_deencredit));
        img2View_deencredit.setVisibility(View.VISIBLE);

    }

    private void clearImg_deencredit(){
        image1Url_deencredit = "";
        image2Url_deencredit = "";
        image1Bitmap_deencredit = null;
        image2Bitmap_deencredit = null;

        img1Ib_deencredit.setImageResource(R.drawable.img_ocr_front_deencredit);
        img2Ib_deencredit.setImageResource(R.drawable.img_ocr_back_deencredit);
    }

    private String getTypeWd_deencredit(){
        switch (selectType_deencredit){
            case CT_IdCard_deencredit:
                return WD_IdCard_deencredit;
            case CT_Passport_deencredit:
                return WD_Passport_deencredit;
            case CT_DrvingLicense_deencredit:
                return WD_DrvingLicense_deencredit;
        }
        return "";
    }

    public void onCameraPermissionAgree_deencredit(){
        if (startCameraRunnable_deencredit !=null) startCameraRunnable_deencredit.run();
    }

    /**
     * 获取图片路径
     */
    private String getImageFilePath_deencredit() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = getSandboxFolderPath_deencredit();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    /**
     * 获取沙盒路径
     */
    private String getSandboxFolderPath_deencredit() {
        String inAppFolder = BaseApplication_deencredit.getInstant().getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += Constant_deencredit.PRODUCT_deencredit;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }

}
